﻿#ifndef MyLog_H
#define MyLog_H

#include <QtCore>
#include <QDir>
#include <QFile>
#include <QFileInfo>

class MyLog : public QObject
{
    Q_OBJECT
public:

    static void Info(QString msg){
        SaveLog("INFO", msg);
    }

    static void Error(QString msg){
        SaveLog("ERROR", msg);
    }

    static void SaveLog(QString type, QString msg){
        static QMutex mutex;
        mutex.lock();

        QString fileName = QString("logs/log-%1.txt").arg(QDate::currentDate().toString("yyyy-MM-dd"));
        QString filePath = GetFilePath(fileName);

        QFile file(filePath);
        if(!file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)){
            return;
        }

        QString info = QString("%1 [%2] -> %3").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz")).arg(type).arg(msg);
        QTextStream txtOutput(&file);
        txtOutput << info << endl;//info写入file
        file.close();

        qDebug() << info;

        mutex.unlock();
    }

    static QString mkMutiDir(const QString path)
    {
        QDir dir(path);
        if (dir.exists(path)){
            return path;
        }
        QString parentDir = mkMutiDir(path.mid(0,path.lastIndexOf('/')));
        QString dirname = path.mid(path.lastIndexOf('/') + 1);
        QDir parentPath(parentDir);
        if ( !dirname.isEmpty() )
            parentPath.mkpath(dirname);//创建dianame路径

        return parentDir + "/" + dirname;
    }

    static QString GetFilePath(const QString path)
    {
        QFileInfo fileInfo(qApp->applicationDirPath() + "/" + path);//QFileInfo类提供独立于系统的文件信息。
        //QFileInfo提供有关文件名和文件系统中的位置（路径）、访问权限以及是目录还是符号链接等信息。还提供文件大小和上次修改/读取时间。
        mkMutiDir(fileInfo.path());
        return qApp->applicationDirPath() + "/" + path;//applicationDirPath()获得可执行文件所在目录
    }
};

#endif // MyLog_H
